package com.bw.mine.login
import android.Manifest
import android.annotation.SuppressLint
import android.app.NotificationChannel
import android.app.NotificationManager
import android.content.Intent
import android.content.pm.PackageManager
import android.net.Uri
import android.os.Build
import android.os.Bundle
import android.provider.Settings
import android.text.Editable
import android.text.TextWatcher
import android.util.Log
import android.widget.Toast
import androidx.lifecycle.lifecycleScope
import com.blankj.utilcode.util.ToastUtils
import com.bw.common.utils.CountdownExample
import com.bw.lib_base.base.BaseActivity
import com.bw.mine.databinding.ActivityRegisterBinding
import com.bw.mine.login.viewmodel.LoginViewModel
import com.hyphenate.EMCallBack
import com.hyphenate.EMError
import com.hyphenate.chat.EMClient
import com.hyphenate.exceptions.HyphenateException
import com.therouter.TheRouter
import com.therouter.router.Route
import dagger.hilt.android.AndroidEntryPoint
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import java.util.Random

@AndroidEntryPoint
@Route(path = "/mine/RegisterActivity")
class RegisterActivity : BaseActivity<ActivityRegisterBinding,LoginViewModel>() {
    private lateinit var username:String
    private lateinit var password:String
    private lateinit var repassword:String
    override fun generatePremission(pageName: String): Array<String> {
        TODO("Not yet implemented")
    }

    override fun setupUI() {

    }

    @SuppressLint("DefaultLocale")
    override fun fetchData() {
        binding.register.setOnClickListener {
            username = binding.phone.text.toString()
            password = binding.password.text.toString()
            repassword = binding.repssword.text.toString()
            if (username.isEmpty() || password.isEmpty()) {
                ToastUtils.showLong("请输入账号和密码")
                return@setOnClickListener
            }
            if (password.length<6){
                ToastUtils.showLong("密码长度不能小于6")
                return@setOnClickListener
            }
            if (password != repassword){
                ToastUtils.showLong("密码不一致")
                return@setOnClickListener
            }
            registerUser(username,password)
        }
        binding.phone.addTextChangedListener(object : TextWatcher {
            override fun beforeTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) {

            }

            override fun onTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) {
                if (p0.toString().matches( "^1[3-9]\\d{9}$".toRegex())){
                    binding.btCode.isEnabled = true
                }
            }

            override fun afterTextChanged(p0: Editable?) {

            }

        })
        binding.btCode.setOnClickListener {
            val random = Random()
            binding.etCode.setText(String.format("%06d", random.nextInt(1000000)))
            val countdown = CountdownExample(60,1,"重新获取验证码")
            countdown.startCountdown(binding.btCode)
        }
    }

    override fun observeData() {
        lifecycleScope.launch {
            vm.loginData
                .collect{
                    if (it!=null){
                        ToastUtils.showLong("注册成功")
                        TheRouter.build("/mine/LoginActivity")
                            .navigation()
                    }
                    Log.d("灌灌灌灌", "空")
                }
        }
    }
    private fun registerUser(username: String, password: String) {
        // 显示加载中
        showLoading()

        // 使用协程在IO线程执行注册
        lifecycleScope.launch(Dispatchers.Main) {
            val result = withContext(Dispatchers.IO) {
                try {
                    // 调用环信注册API
                    EMClient.getInstance().createAccount(username, password)
                    Result.success(Unit)
                } catch (e: Exception) {
                    // 处理注册失败
                    val errorCode = (e as? HyphenateException)?.errorCode ?: -1
                    val errorMsg = getErrorMessage(errorCode)
                    Result.failure(Exception(errorMsg))
                }
            }

            // 隐藏加载中
            hideLoading()

            // 处理注册结果
            if (result.isSuccess) {
                vm.getRequest(password, username)
                Log.d("TAG", "registerUser: 环信注册成功")
                finish()
            } else {
                val errorMessage = result.exceptionOrNull()?.message ?: "注册失败"
                Log.d("TAG", "registerUser: ${errorMessage.toString()}")
                Toast.makeText(this@RegisterActivity, errorMessage, Toast.LENGTH_SHORT).show()
            }
        }
    }

    private fun getErrorMessage(errorCode: Int): String {
        return when (errorCode) {
            EMError.USER_ALREADY_EXIST -> "用户已存在"
            EMError.USER_AUTHENTICATION_FAILED -> "认证失败"
            EMError.USER_ILLEGAL_ARGUMENT -> "用户名不合法"
            else -> "注册失败，错误码: $errorCode"
        }
    }

    private fun showLoading() {
        // 显示加载对话框
    }

    private fun hideLoading() {
        // 隐藏加载对话框
    }
    override fun handleEvent() {

    }

    override val mLayoutResId: Int
        get() = TODO("Not yet implemented")
}